package com.tlgen.orm.support.chain;

import com.tlgen.orm.components.rest.model.RequestMethodAndUrl;
import com.tlgen.orm.components.sqlXml.SqlExecutor;
import com.tlgen.orm.utils.xml.SqlXmlLoader;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class SqlExecutionStage implements ExecutionStage {

    @Override
    public boolean shouldExecute(RequestMethodAndUrl requestMethodAndUrl) {
        // 只执行带@SQL注解的方法
        return requestMethodAndUrl.getHasSQLAnnotation();
    }

    @Override
    public Object execute(HttpServletRequest request,
                          RequestMethodAndUrl requestMethodAndUrl,
                          Map<String, Object> params,
                          Object previousResult) throws Exception {
        // 如果实现类执行后有结果，可以整合到参数中
        if (previousResult != null) {
            params.put("__implResult", previousResult);
        }

        // 执行SQL
        String sql = SqlXmlLoader.parserQLXMLByMethodName(requestMethodAndUrl.getMethodName(), params);
        return SqlExecutor.create().executeSql(sql, params, requestMethodAndUrl.getReturnType());
    }

    @Override
    public boolean shouldTerminate() {
        // SQL执行后终止流程
        return true;
    }

}